package com.example.hello;

import com.example.hello.client.Container.BootstrapContainerState;
import com.vaadin.shared.Connector;
import com.vaadin.ui.AbstractComponentContainer;
import com.vaadin.ui.Component;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class BootstrapContainer extends AbstractComponentContainer {

    public BootstrapContainer(Component... widgets) {
        for (Component c : widgets)
            addWidget(c);
    }

    public List<Component> getWidgets() {
        List<Component> widgets = new LinkedList<Component>();
        for (Connector connector : getState().getWidgets()) {
            widgets.add((Component) connector);
        }

        return widgets;
    }

    public void setWidgets(List<Component> widgets) {
        List<Connector> connectorList = new LinkedList<Connector>();
        for (Component widget : widgets) {
            connectorList.add(widget);
        }

        getState().setWidgets(connectorList);
    }

    @Override
    protected BootstrapContainerState getState() {
        return (BootstrapContainerState) super.getState();
    }

    public void addWidget(Component widget) {
        addWidget(widget, getWidgets().size());
    }

    private void addWidget(Component widget, int index) {
        if (widget.getParent() != null) {
            throw new IllegalArgumentException("Given widget already has a parent component");
        }

        getState().addWidget(widget, index);
        super.addComponent(widget);

        markAsDirty();
    }

    public void replaceWidget(Component oldWidget, Component newWidget) {
        if (!getState().getWidgets().contains(oldWidget)) {
            throw new IllegalArgumentException("Given old widget does not exist in this group");
        }

        int oldIndex = getState().getWidgets().indexOf(oldWidget);

        if (oldIndex == -1) {
            return;
        }

        removeWidget(oldWidget);
        addWidget(newWidget, oldIndex);
    }

    public boolean removeWidget(Component widget) {
        if (!getState().getWidgets().contains(widget)) {
            return false;
        }

        getState().removeWidget(widget);
        super.removeComponent(widget);

        markAsDirty();
        return true;
    }

    public void removeAllWidgets() {
        getState().getWidgets().clear();
        super.removeAllComponents();

        markAsDirty();
    }

    @Override
    public void replaceComponent(Component oldComponent, Component newComponent) {
        throw new UnsupportedOperationException("Use replaceWidget method instead");
    }

    @Override
    public int getComponentCount() {
        return getWidgets().size();
    }

    @Override
    public Iterator<Component> iterator() {
        return getWidgets().iterator();
    }

}
